<template>
  <div class="wangeditor-editor">
    <Toolbar style="border-bottom: 1px solid #cdcdcd" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
    <Editor
      :style="{ height: editorHeight }"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
    />
  </div>
</template>
<script lang="ts" setup name="WangeditorEditor">
import type { PropType } from 'vue'
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { onBeforeUnmount, ref, shallowRef, onMounted, computed } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { IDomEditor, IToolbarConfig, IEditorConfig } from '@wangeditor/editor'
import { uploadImgAddress } from '@/utils/axios/request'
import { message } from 'ant-design-vue'

type InsertFnType = (url: string, alt?: string, href?: string) => void

const props = defineProps({
  mode: { type: String, default: 'default' },
  editorHeight: { type: String, default: '320px' },
  modelValue: { type: String, default: '' }
})

const emit = defineEmits(['update:modelValue'])
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = computed({
  get() {
    return props.modelValue
  },
  set(value: string) {
    emit('update:modelValue', value)
  }
})

// 模拟 ajax 异步获取内容
onMounted(() => {})

const toolbarConfig: Partial<IToolbarConfig> = {
  excludeKeys: ['group-video']
}

const editorConfig: any = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      server: uploadImgAddress,
      fieldName: 'file',
      meta: {
        fileType: 2
      },
      maxFileSize: 10 * 1024 * 1024, // 10M
      // 自定义插入图片
      customInsert(res: any, insertFn: InsertFnType) {
        if (res.code == '200') {
          // TS 语法
          // customInsert(res, insertFn) {                  // JS 语法
          // res 即服务端的返回结果
          let url = res.result || ''
          // 从 res 中找到 url alt href ，然后插入图片
          insertFn(url)
        }
      },

      // 上传错误，或者触发 timeout 超时
      onError(file: File, err: any, res: any) {
        message.error('文件上传失败')
      }
    }
  }
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

// 编辑器创建完毕时的回调函数
const handleCreated = (editor: IDomEditor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
</script>
<style lang="less" scoped>
.wangeditor-editor {
  border: 1px solid #cdcdcd;
  z-index: 999;
}
</style>
